<template>
  <div class="perform-item">
    <div class="perform-item--content">
      <item-list
        ref="itemList"
        v-if="showList"
        :itemList="itemList"
        :planTime="planTime"
        :hideBtn="hideBtn"
        :orderStatus="orderStatus"
        :btnJurisdiction="btnJurisdiction"
        :orderType="orderType"
        :showOnly="showOnly"
        :pageType="pageType"
        @handleDelete="doDelete"
        @handleSave="doSave"
      ></item-list>
      <el-tooltip
        class="item"
        effect="dark"
        :disabled="showSaveBtn"
        :content="saveTitle"
        placement="top-start"
      >
        <div class="btnDiv">
          <el-button
            class="perform-item-add"
            v-if="!hideBtn"
            icon="el-icon-plus"
            @click="addItem"
            :disabled="!showSaveBtn"
            >新增执行信息</el-button
          >
        </div>
      </el-tooltip>
    </div>
  </div>
</template>

<script>
import {
  performListApi, //获取-工单执行列表
  performInsertApi, //新增\保存-工单执行
  performDetailsApi, //获取详情-工单执行
  performDeleteApi,
} from "@/api/orderManagement/common";

import itemList from "./itemList";
var itemNum = 1;
export default {
  props: {
    hideBtn: {
      type: Boolean,
      default: false,
    },
    orderType: {
      type: String,
      default: "",
    },
    orderStatus: {
      type: String,
      default: "",
    },
    pageType: {
      type: String,
      default: "",
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    planTime: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //仅作为信息展示
    showOnly: {
      type: Boolean,
      default: false,
    },
    performData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    btnJurisdiction: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  components: { itemList },
  data() {
    return {
      itemList: [],
      saveItemList: [],
      editFormData: {},
      showList: true,
      isGetData: false,
      orderId: null,
    };
  },
  watch: {
    formData: {
      handler(val) {
        this.init();
      },
      deep: true,
    },
    performData: {
      handler(val) {
        this.itemList = JSON.parse(JSON.stringify(val)) || [];
        if (
          this.itemList.length == 0 &&
          !this.showOnly &&
          this.orderType == "overhaul"
        ) {
          this.addItem();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    showSaveBtn() {
      if (["defect", "maintain"].includes(this.orderType)) {
        //, "overhaul"
        return (
          this.$store.getters["isBtnAuth"]("addExecute") &&
          this.$utils.getJurisdiction(this.btnJurisdiction, "addExecute")
        );
      } else {
        return true;
      }
    },
    saveTitle() {
      return this.$utils.getJurisdictionContent(
        this.btnJurisdiction,
        "addExecute",
        this.$store.getters["isBtnAuth"]("addExecute")
      );
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let { id, status } = this.formData;
      //把orderId保存下来
      if (this.orderId != id) {
        this.orderId = id || "";
        // this.getItemList();
      }
      if (this.orderType != "" && this.orderType != "overhaul") {
        this.getDataJudge();
      }
    },
    //判断是否需要获取执行信息
    getDataJudge() {
      if (this.orderId && this.isGetData == false) {
        this.isGetData = true;
        this.getItemList();
      }
    },
    async getItemList() {
      let form = {
        orderId: this.orderId,
        orderType: this.orderType,
      };
      let res = await performListApi(form);
      let data = res.data || [];
      this.saveItemList = data;
      if (data.length != 0) {
        data.map((i) => {
          let { factStartTime, factEndTime } = i;
          i.factTime = [factStartTime, factEndTime];
        });
        this.itemList = data;
        this.$emit("changePerformData", true);
        this.showList = true;
      } else {
        this.itemList = data;
        this.$emit("changePerformData", false);
        if (!this.showOnly) {
          this.addItem();
        }
      }
    },
    async getPerformData() {
      return this.saveItemList;
    },
    isComplete() {
      let result = false;
      for (let i = 0; i < this.saveItemList.length; i++) {
        if (this.saveItemList[i].id) {
          result = true;
          break;
        }
      }
      return result;
    },
    //新增议题
    addItem() {
      this.editFormData = { download: 1 };
      let form = {
        id: "",
        trueStatus: "1",
        remainStatus: "0",
        runStatus: "1",
        orderId: this.orderId,
        orderType: this.orderType,
      };
      form.equipmentId = this.formData.equipmentId;
      form.equipmentName = this.formData.equipmentName;
      form.majorId = this.formData.major;
      form.factStartTime;
      form.factStartTime = this.$utils.getCurrentDate("minutes");
      form.factEndTime = this.$utils.TimeFormat(new Date(form.factStartTime).getTime()+24*3600*1000,3);
      this.itemList.push(form);
      this.showList = true;
    },
    //保存执行信息
    async doSave(data, index) {
      data.factStartTime = data.factTime[0];
      data.factEndTime = data.factTime[1];
      data.orderId = this.orderId;
      data.orderType = this.orderType;
      data.sort = index;
      delete data.factTime;
      if (this.orderType == "overhaul") {
        //大修工单的执行信息
        this.$emit("savePerform", data, index);
      } else {
        if (this.orderType == "defect") {
          try {
            //this.$refs.itemList.getImageFile(index);
            performInsertApi(data, this.orderType).then((res) => {
              // 如果有缺陷工单打印预览，则更新打印预览数据
              let printReview = localStorage.getItem("print-review");
              if(printReview) {
                printReview = JSON.parse(printReview);
                let index = printReview.insturn.findIndex(i => {
                  return i.defectExecuteId === data.defectExecuteId
                })
                if( index !== -1) {
                  printReview.insturn[index].context = data.context;
                  printReview.insturn[index].orderExecutePart = data.orderExecutePart;
                  localStorage.setItem("print-review",JSON.stringify(printReview));
                }
              }
              this.$refs.itemList.saveAttach(index, res.data);
              this.$utils.addOperateLog(this.formData.id, "保存-执行信息");
              this.isGetData = false;
              this.$message.success("操作成功！");
              this.$utils.updateStorage();
              this.getItemList();
            });
          } catch (error) {
            //this.$message.warning("请上传完工图片");
          }
        } else {
          performInsertApi(data, this.orderType).then((res) => {
            this.$refs.itemList.saveAttach(index, res.data);
            this.$utils.addOperateLog(this.formData.id, "保存-执行信息");
            this.isGetData = false;
            this.$message.success("操作成功！");
            this.$utils.updateStorage();
            this.getItemList();
          });
        }
      }
    },
    setAttachType(index, id) {
      this.$refs.itemList.saveAttach(index, id);
    },
    //获取
    getAttachList() {
      try {
        this.$refs.itemList.getImageFile();
      } catch (error) {
        this.$message.warning(error);
        throw error;
      }
    },
    //删除
    async doDelete(item, num) {
      let executeId = "";
      if (this.orderType == "overhaul") {
        //大修工单的执行信息
        executeId = item.id;
      } else {
        executeId = item.orderExecuteId;
      }
      if (executeId) {
        this.$confirm(`是否删除该议题？删除后无法恢复`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            if (this.orderType == "overhaul") {
              //大修工单的执行信息
              this.$emit("deletePerform", item, num);
            } else {
              let form = {
                orderType: this.orderType,
                orderId: this.formData.id,
                orderExecuteId: item.orderExecuteId,
              };
              performDeleteApi(form).then((res) => {
                this.$refs.itemList.deleteAttach(num);
                this.isGetData = false;
                this.$utils.addOperateLog(this.formData.id, "删除-执行信息");
                this.$message.success("删除成功");
                this.showList = false;
                this.init();
              });
            }
          })
          .catch((e) => {});
      } else {
        this.itemList = await this.$refs.itemList.getListData(num);
      }
    },
  },
};
</script>

<style lang="less">
.perform-item {
  margin: 10px 0;
  .perform-item--content {
    padding: 10px 10px;
    /* background-color: #fafafa; */
  }
  .btnDiv {
    display: inline-block;
    width: 100%;
  }
  .perform-item-add {
    line-height: 6px;
    padding: 6px 10px;
    margin: 10px 0;
    width: 100%;
    min-width: 200px;
    // border-color: #e1e1e1;
    // color: #909399;
  }
}
</style>
